package telsoft.app.form;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

import telsoft.admin.util.*;
import telsoft.app.util.*;
import telsoft.comm.protocol.*;
import telsoft.swing.*;
import telsoft.util.*;

/**
 *
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2009</p>
 *
 * <p>Company: Telsoft</p>
 *
 * @author HuongNV
 * @version 1.0
 */

public class DialogLOV extends JXDialog implements ActionListener, KeyListener, MouseListener
{
    VectorTable mtblLOVData;
    JLabel lblSearch = new JLabel();
    JTextField txtSearch = new JTextField();
    JXButton btnOK = new JXButton();
    JXButton btnCancel = new JXButton();
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    GridBagLayout gridBagLayout2 = new GridBagLayout();
    BorderLayout borderLayout1 = new BorderLayout();

    String mstrQuery;
    Vector mvtColName;
    Vector mvtLOVData;
    Vector vtFlag;
    Vector mvtSelectedItem;
    String mstrFilter = "";
    boolean bIsFinal;
    int iCurrentRow = 0;
    public boolean bDataLoaded = false;
    private int miSearchCol = 0;
    private int[] miLovCol;

    public DialogLOV(Component pfrmParent, Vector pvtColName, String pstrQuery)
    {
        super(pfrmParent, true);
        try
        {
            mstrQuery = pstrQuery;
            mvtColName = pvtColName;
            if(pvtColName != null && pvtColName.size() > 0)
            {
                miLovCol = new int[pvtColName.size()];
                for(int i = 0;i < miLovCol.length;i++)
                {
                    miLovCol[i] = i;
                }
            }
            jbInit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    public DialogLOV(Component pfrmParent, Vector pvtColName, Vector pvtData)
    {
        super(pfrmParent, true);
        try
        {
            mvtColName = pvtColName;
            mvtLOVData = pvtData;
            if(pvtColName != null && pvtColName.size() > 0)
            {
                miLovCol = new int[pvtColName.size()];
                for(int i = 0;i < miLovCol.length;i++)
                {
                    miLovCol[i] = i;
                }
            }
            jbInit_Data();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
        }
    }

    public DialogLOV(Component pfrmParent, Vector pvtColName, Vector pvtData, int iSearchCol)
    {
        this(pfrmParent, pvtColName, pvtData);
        miSearchCol = iSearchCol;
    }

    public DialogLOV(Component pfrmParent, int[] iLovCol, Vector pvtColName, Vector pvtData,
        int iSearchCol)
    {
        super(pfrmParent, true);
        try
        {
            mvtColName = pvtColName;
            mvtLOVData = pvtData;
            miLovCol = iLovCol;
            jbInit_Data();
            miSearchCol = iSearchCol;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
        }
    }

    /**
     * @purpose: Initialized values DialogLOV
     * @logic
     * 1.Create column in LOV
     * 2.Create panel button
     * 3. Create panel search
     * 4.add listener
     * 5.applied skin
     * 6.load data default
     * @return none
     */
    /////////////////////////////////////////////////////////////////////////////
    private void jbInit() throws Exception
    {
        setSize(new Dimension(464, 418));
        this.getContentPane().setLayout(borderLayout1);
        mtblLOVData = new VectorTable(mvtColName.size());
        JTableContainer vtblContainer = new JTableContainer(mtblLOVData, "", true);
        //1.Create column in LOV
//		for(int i = 0;i < mvtColName.size();i++)
//		{
//			mtblLOVData.addColumn((String)mvtColName.elementAt(i),i,false);
//		}
        for(int i = 0;i < miLovCol.length;i++)
        {
            mtblLOVData.addColumn((String)mvtColName.elementAt(i), miLovCol[i], false);
        }
        //2.Create panel button
        JPanel vpnlButton = new JPanel();
        vpnlButton.setLayout(gridBagLayout1);

        vpnlButton.setMinimumSize(new Dimension(150, 28));
        vpnlButton.setPreferredSize(new Dimension(150, 28));
        vpnlButton.add(btnOK, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        vpnlButton.add(btnCancel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        //3. Create panel search
        JPanel vpnlSearch = new JPanel();
        vpnlSearch.setLayout(gridBagLayout2);
        vpnlSearch.add(lblSearch, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
        vpnlSearch.add(txtSearch, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        vpnlSearch.add(vpnlButton, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.EAST,
            GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
        txtSearch.setBounds(new Rectangle(15, 57, 209, 24));
        txtSearch.setDocument(new JUpperCaseDocument());
        btnOK.setBounds(new Rectangle(270, 59, 90, 20));
        btnCancel.setBounds(new Rectangle(384, 58, 59, 20));
        this.getContentPane().add(vtblContainer, BorderLayout.CENTER);
        this.getContentPane().add(vpnlSearch, BorderLayout.NORTH);
        this.getRootPane().setDefaultButton(btnOK);
        //4.add listener
        btnOK.addActionListener(this);
        btnCancel.addActionListener(this);
        txtSearch.addKeyListener(this);
        mtblLOVData.addKeyListener(this);
        mtblLOVData.addMouseListener(this);
        //5.applied skin
        this.setModal(true);
        updateLanguage();
        //6.load data default
        form_load();
    }

    /**
     * @purpose: Initialized values DialogLOV
     * @logic
     * 1.Create column in LOV
     * 2.Create panel button
     * 3. Create panel search
     * 4.add listener
     * 5.applied skin
     * 6.load data default
     * @return none
     */
    /////////////////////////////////////////////////////////////////////////////
    private void jbInit_Data() throws Exception
    {

        setSize(new Dimension(464, 418));

        this.getContentPane().setLayout(borderLayout1);
        mtblLOVData = new VectorTable(mvtLOVData.size());
        JTableContainer vtblContainer = new JTableContainer(mtblLOVData, "", true);
        //1.Create column in LOV
        for(int i = 0;i < mvtColName.size();i++)
        {
            mtblLOVData.addColumn((String)mvtColName.elementAt(i), miLovCol[i], false);
        }
        //2.Create panel button
        JPanel vpnlButton = new JPanel();
        vpnlButton.setLayout(gridBagLayout1);

        vpnlButton.setMinimumSize(new Dimension(150, 28));
        vpnlButton.setPreferredSize(new Dimension(150, 28));
        vpnlButton.add(btnOK, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        vpnlButton.add(btnCancel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        //3. Create panel search
        JPanel vpnlSearch = new JPanel();
        vpnlSearch.setLayout(gridBagLayout2);
        vpnlSearch.add(lblSearch, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
        vpnlSearch.add(txtSearch, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        vpnlSearch.add(vpnlButton, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.EAST,
            GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
        txtSearch.setBounds(new Rectangle(15, 57, 209, 24));
        txtSearch.setDocument(new JUpperCaseDocument());
        btnOK.setBounds(new Rectangle(270, 59, 90, 20));
        btnCancel.setBounds(new Rectangle(384, 58, 59, 20));
        this.getContentPane().add(vtblContainer, BorderLayout.CENTER);
        this.getContentPane().add(vpnlSearch, BorderLayout.NORTH);
        this.getRootPane().setDefaultButton(btnOK);
        //4.add listener
        btnOK.addActionListener(this);
        btnCancel.addActionListener(this);
        txtSearch.addKeyListener(this);
        mtblLOVData.addKeyListener(this);
        mtblLOVData.addMouseListener(this);
        //
        mtblLOVData.setHeaderSort(true);
        //5.applied skin
        this.setModal(true);
        Skin.applySkin(this);
        updateLanguage();
        //6.load data default
        Thread threadInit = new Thread()
        {
            public void run()
            {
                setDataToLov();
            }
        };
        threadInit.start();
    }

    public void actionPerformed(ActionEvent ae)
    {
        Object obj = ae.getSource();
        try
        {
            if(obj == btnOK)
            {
                int vintSelectedRow = mtblLOVData.getSelectedRow();
                if(vintSelectedRow < 0)
                {
                    throw new AppException(getDictionary().getString("Label"));
                }
                mvtSelectedItem = mtblLOVData.getRow(vintSelectedRow);
                this.dispose();
            }
            else if(obj == btnCancel)
            {
                mvtSelectedItem = null;
                this.dispose();
            }
        }
        catch(AppException e)
        {
            MessageBox.showMessageDialog(this, e.getMessage(), Global.APP_NAME, MessageBox.ERROR_MESSAGE);
            if(e.getReason().equals(getDictionary().getString("Label")))
            {
                this.txtSearch.requestFocus();
            }
        }
        catch(Exception e)
        {
            MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
        }
    }

    ////////////////////////////////////////////////////////////////////////
    /**
     * @purpose:Create Function query from server
     * logic
     * 1.Call getLOVData
     * 2.Query data from server
     * 3.Store param
     */
    ////////////////////////////////////////////////////////////////////////
    public void form_load() throws AppException
    {
        try
        {
            if(mstrQuery == null || mstrQuery.equals(""))
            {
                return;
            }
            bDataLoaded = false;
            loadToLov();
            bDataLoaded = true;
        }
        catch(Exception e)
        {
            throw new AppException(e, "form_load");
        }
    }

    public void setLOVData(Vector pvtData)
    {
        mtblLOVData.setData(pvtData);
        mvtLOVData = pvtData;
    }

    public Vector showLOV(String pstrSearch, boolean pblnEnfDisplay)
    {
        return showLOV(pstrSearch, pblnEnfDisplay, true);
    }

    public Vector showLOV(String pstrSearch, boolean pblnEnfDisplay, boolean pblnForceShow)
    {
        return showLOV(pstrSearch, pblnEnfDisplay, pblnForceShow, miSearchCol);
    }

    /**
     *
     * @param pstrSearch String
     * @param pblnEnfDisplay boolean
     * @param pblnForceShow boolean
     * @param iSearchCol int
     * @return Vector
     * @author Hungdv
     * @since 29/11/2007
     */
    public Vector showLOV(String pstrSearch, boolean pblnEnfDisplay, boolean pblnForceShow,
        int iSearchCol)
    {
        miSearchCol = iSearchCol;
        txtSearch.setText(pstrSearch);
        txtSearch.requestFocus();
        keyReleased();
        if((mtblLOVData.getData().size() == 1) && !pblnEnfDisplay)
        {
            return mtblLOVData.getRow(0);
        }
        if(pblnForceShow)
        {
            WindowManager.centeredWindow(this);
        }
        return mvtSelectedItem;
    }

    public void keyTyped(KeyEvent e)
    {
    }

    /**
     * @logic
     * 1.Invoked when a key has been pressed.
     * 2.See the class description for {@link KeyEvent} for a definition of a key pressed event.
     */
    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyCode() == e.VK_ENTER)
        {
            if(e.getSource() == mtblLOVData)
            {
                mtblLOVData.setRowSelectionInterval(iCurrentRow, iCurrentRow);
            }
            btnOK.doClick();
        }
        if(e.getKeyCode() == e.VK_DOWN && e.getSource() != mtblLOVData)
        {
            if(mtblLOVData != null)
            {
                mtblLOVData.requestFocus();
            }
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    /**
     * 1.Invoked when a key has been released.
     * 2.See the class description for {@link KeyEvent} for a definition of a key released event.
     */
    ////////////////////////////////////////////////////////////////////////////

    public void keyReleased(KeyEvent e)
    {
        if(!e.isActionKey() && e.getSource() != mtblLOVData)
        {
            keyReleased();
        }
        else if((e.getKeyCode() == e.VK_DOWN ||
            e.getKeyCode() == e.VK_UP) && e.getSource() == mtblLOVData && mtblLOVData != null)
        {
            iCurrentRow = mtblLOVData.getSelectedRow();
        }
    }

    private void keyReleased()
    {
        if(mtblLOVData != null && mtblLOVData.getData() != null)
        {
            removeFromLOV(txtSearch.getText().trim());
            if(mtblLOVData.getData().size() > 0)
            {
                mtblLOVData.setRowSelectionInterval(0, 0);
            }
        }

    }

    public void mouseClicked(MouseEvent e)
    {
        if(e.getClickCount() == 2)
        {
            btnOK.doClick();
        }
    }

    public void mouseEntered(MouseEvent e)
    {

    }

    public void mouseExited(MouseEvent e)
    {

    }

    public void mousePressed(MouseEvent e)
    {

    }

    public void mouseReleased(MouseEvent e)
    {

    }

    private void removeFromLOV(String pstrFrom)
    {
        if(mvtLOVData == null)
        {
            return;
        }
        pstrFrom = mstrFilter + pstrFrom;
        Vector vvtEqual = null;
        if(pstrFrom.equals(""))
        {
            mtblLOVData.setData(mvtLOVData);
        }
        else
        {
            Vector vvtTempData = (Vector)mvtLOVData.clone();
            int i = 0;

            while(i < vvtTempData.size())
            {
                Vector vvtSelectedRow = (Vector)vvtTempData.elementAt(i);
                i++;
                String vstrCode = (String)vvtSelectedRow.elementAt(miSearchCol);
                String vstrName = (String)vvtSelectedRow.elementAt(1);
                if(vstrCode.equalsIgnoreCase(pstrFrom) || vstrName.equalsIgnoreCase(pstrFrom))
                {
                    vvtEqual = vvtSelectedRow;
                    break;
                }
                if(vstrCode.toUpperCase().indexOf(pstrFrom) < 0 && vstrName.toUpperCase().indexOf(pstrFrom) < 0)
                {
                    vvtTempData.remove(--i);
                }
            }
            if(vvtEqual != null)
            {
                vvtTempData = new Vector();
                vvtTempData.add(vvtEqual);
            }
            mtblLOVData.setData(vvtTempData);
        }
    }

    public Vector getLOVData()
    {
        return mvtLOVData;
    }

    public Vector getLOVColumnName()
    {
        return mvtColName;
    }

    public void setFilter(String pstrFilter)
    {
        mstrFilter = pstrFilter;
    }

    public void setQuery(String pstrQuery) throws AppException
    {
        mstrQuery = pstrQuery;
        form_load();
    }

    ////////////////////////////////////////////////////////////////////////////
    /**
     * @purpose: Set language to all label and title on GUI
     * @param none
     * @logic
     * 1.Update language of title Form
     * 2.Update language of Buttons
     * @return none
     * @throws AppException
     * @since not assigned
     */
    /////////////////////////////////////////////////////////////////////////////

    public void updateLanguage() throws AppException
    {
        setTitle(getDictionary().getString("Title"));
        lblSearch.setText(getDictionary().getString("lblSearch"));
        btnOK.setText(getDictionary().getString("btnOK"));
        btnOK.setMnemonic(getDictionary().getString("btnOK.Mnemonic").charAt(0));
        btnCancel.setText(getDictionary().getString("btnCancel"));
        btnCancel.setMnemonic(getDictionary().getString("btnCancel.Mnemonic").charAt(0));
        Skin.applySkin(this);
    }

    ////////////////////////////////////////////////////////////////////////////
    /**
     * @purpose:Fill langguage label column  Table
     * @param:Vector
     * @since not assigned
     */
    /////////////////////////////////////////////////////////////////////////////

    public void languageColumn(Vector vtColName)
    {
        mvtColName = vtColName;
        for(int i = 0;i < vtColName.size();i++)
        {
            mtblLOVData.setColumnNameEx(vtColName.elementAt(i).toString(), i);
        }
    }

    public synchronized void setDataToLov()
    {
        bDataLoaded = false;
        mtblLOVData.setData(mvtLOVData);
        bDataLoaded = true;
    }

    public synchronized void loadToLov()
    {
        try
        {
            DataTransmit prmRequest = new DataTransmit();
            prmRequest.setString("In.strQuery", mstrQuery);
            //2.Query data from server
            DataTransmit prmResponse = AppClient.sendRequest("CommonLOVBean", "getLOVData", prmRequest);
            //3.Store param
            mvtLOVData = (Vector)prmResponse.getReturn();
            if(mvtLOVData != null)
            {
                mtblLOVData.setData(mvtLOVData);
            }
            else
            {
                mtblLOVData.setData(new Vector());
            }
        }
        catch(Exception ex)
        {
            MessageBox.showMessageDialog(this, ex, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
        }
    }

    public void setSearchCol(int iCol)
    {
        if(iCol > -1)
        {
            miSearchCol = iCol;
        }
    }
}
